﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Nop.Admin.Models.WindAlert;
using Nop.Admin.WindAlert;
using Nop.Core;
using Nop.Core.Domain.Common;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.Directory;
using Nop.Core.Domain.WindAlert;
using Nop.Services.Directory;
using Nop.Services.ExportImport;
using Nop.Services.Localization;
using Nop.Services.Logging;
using Nop.Services.Security;
using Nop.Services.Seo;
using Nop.Services.WindAlert;
using Nop.Web.Framework;
using Nop.Web.Framework.Controllers;
using Nop.Services.Helpers;
using Nop.Web.Framework.Kendoui;

namespace Nop.Admin.Controllers
{
    public partial class WSpotsGroupController : BaseAdminController
    {
        #region Fields
        private readonly ILanguageService _languageService;
        private readonly ILocalizationService _localizationService;
        private readonly ILocalizedEntityService _localizedEntityService;
        private readonly ICustomerActivityService _customerActivityService;
        private readonly IExportManager _exportManager;
        private readonly IWorkContext _workContext;
        private readonly IPermissionService _permissionService;
        private readonly AdminAreaSettings _adminAreaSettings;
        private readonly IUrlRecordService _urlRecordService;
        private readonly IAlertService _alertService;
        private readonly ISpotService _spotService;
        private readonly ICameraService _cameraService;
        private readonly IDateTimeHelper _dateTimeHelper;

        private readonly ICountryService _countryService;
        private readonly IStateProvinceService _stateProvinceService;

        #endregion

        #region Constructors
        
        public WSpotsGroupController(ILanguageService languageService,
            ILocalizationService localizationService, ILocalizedEntityService localizedEntityService,
            ICustomerActivityService customerActivityService, 
            IExportManager exportManager, IWorkContext workContext,
            IPermissionService permissionService,
            AdminAreaSettings adminAreaSettings, IUrlRecordService urlRecordService, 
            IAlertService alertService, 
            ISpotService spotService,
            ICameraService cameraService,
            IDateTimeHelper dateTimeHelper
            , ICountryService countryService, IStateProvinceService stateProvinceService)
        {
            this._languageService = languageService;
            this._localizationService = localizationService;
            this._localizedEntityService = localizedEntityService;
            this._customerActivityService = customerActivityService;
            this._exportManager = exportManager;
            this._workContext = workContext;
            this._permissionService = permissionService;
            this._adminAreaSettings = adminAreaSettings;
            this._urlRecordService = urlRecordService;
            this._alertService = alertService;
            this._spotService = spotService;
            this._cameraService = cameraService;
            this._dateTimeHelper = dateTimeHelper;
            this._countryService = countryService;
            this._stateProvinceService = stateProvinceService;
        }

        #endregion

        #region Utilities

        #endregion

        #region Create / Edit / Delete / List

        public ActionResult Index()
        {
            return RedirectToAction("List");
        }

        public ActionResult List()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();
            return View();
        }

        [HttpPost]
        public ActionResult List(DataSourceRequest command)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();
            var alerts = _alertService.GetAllSpotsGroups(command.Page - 1, command.PageSize);
            var gridModel = new DataSourceResult
            {
                Data = alerts.Select(x => x.ToModel()),
                Total = alerts.TotalCount
            };
            return new JsonResult
            {
                Data = gridModel
            };
        }

        public ActionResult Create()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageAcl))
                return AccessDeniedView();

            var model = new SpotsGroupModel();
            //spot
            model.AvailableSpots = _spotService.GetAllSpots()
                .Select(s => s.ToModel())
                .ToList();
            model.SelectedSpotsIds = new int[0];
           
            //default values
            model.Published = true;
            return View(model);
        }

        [HttpPost, ParameterBasedOnFormName("save-continue", "continueEditing")]
        public ActionResult Create(SpotsGroupModel model, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageAcl))
                return AccessDeniedView();


            if (ModelState.IsValid)
            {
                var spotsGroup = model.ToEntity();
            
                _alertService.InsertSpotsGroup (spotsGroup);

                //spots
                var allSpots = _spotService.GetAllSpots();
                foreach (var spot in allSpots)
                    if (model.SelectedSpotsIds != null && model.SelectedSpotsIds.Contains(spot.Id))
                        spotsGroup.Spots.Add(spot);
                _alertService.UpdateSpotsGroup(spotsGroup);

                //activity log
                _customerActivityService.InsertActivity("AddNewSpotsGroup", _localizationService.GetResource("ActivityLog.AddNewSpotsGroup"), spotsGroup.Name);

                SuccessNotification(_localizationService.GetResource("Admin.WindAlert.Spots.Added"));
                return continueEditing ? RedirectToAction("Edit", new { id = spotsGroup.Id }) : RedirectToAction("List");
            }

            //cameras
            model.AvailableSpots = _spotService.GetAllSpots()
                .Select(cr => cr.ToModel())
                .ToList();
            model.SelectedSpotsIds = new int[0];

            //default values
            model.Published = true;
            return View(model);
        }

        public ActionResult Edit(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            var spotsGroup = _alertService.GetSpotsGroupById(id);
            if (spotsGroup == null)
                //No spot found with the specified id
                return RedirectToAction("List");

            var model = spotsGroup.ToModel();

            //cameras
            model.AvailableSpots = _spotService
                .GetAllSpots()
                .Select(s => s.ToModel())
                .ToList();
            model.SelectedSpotsIds = spotsGroup.Spots.Select(s => s.Id).ToArray();

            return View(model);
        }

        [HttpPost, ParameterBasedOnFormName("save-continue", "continueEditing")]
        public ActionResult Edit(SpotsGroupModel model, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            var spotsGroup = _alertService.GetSpotsGroupById(model.Id);
            if (spotsGroup == null)
                //No spot found with the specified id	
                return RedirectToAction("List");

            if (ModelState.IsValid)
            {

                spotsGroup = model.ToEntity(spotsGroup);
               
                _alertService.UpdateSpotsGroup(spotsGroup);
                //spots
                var allSpots = _spotService.GetAllSpots();
                foreach (var spot in allSpots)
                {
                    if (model.SelectedSpotsIds != null &&
                        model.SelectedSpotsIds.Contains(spot.Id))
                    {
                        //new role
                        if (spotsGroup.Spots.Count(s => s.Id == spot.Id) == 0)
                            spotsGroup.Spots.Add(spot);
                    }
                    else
                    {
                        //removed role
                        if (spotsGroup.Spots.Count(s => s.Id == spot.Id) > 0)
                            spotsGroup.Spots.Remove(spot);
                    }
                }
                _alertService.UpdateSpotsGroup(spotsGroup);

                //activity log
                _customerActivityService.InsertActivity("EditSpotsGroup", _localizationService.GetResource("ActivityLog.EditSpotsGroup"), spotsGroup.Name);

                SuccessNotification(_localizationService.GetResource("Admin.WindAlert.Spots.Updated"));
                if (continueEditing)
                {
                    //selected tab
                    SaveSelectedTabIndex();

                    return RedirectToAction("Edit", new { id = spotsGroup.Id });
                }
                else
                {
                    return RedirectToAction("List");
                }
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult Delete(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            var spotsGroup = _alertService.GetSpotsGroupById(id);
            if (spotsGroup == null)
                //No spot found with the specified id	
                return RedirectToAction("List");
            _alertService.DeleteSpotsGroup(spotsGroup);

            //activity log
            _customerActivityService.InsertActivity("DeleteSpotsGroup", _localizationService.GetResource("ActivityLog.DeleteSpotsGroup"), spotsGroup.Name);

            SuccessNotification(_localizationService.GetResource("Admin.WindAlert.Spots.Deleted"));
            return RedirectToAction("List");
        }
        #endregion   
   
    }
}
